package com.atguigu.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockDemo {
    private final Lock lock = new ReentrantLock();

    public static void main(String[] args) {
        LockDemo lockDemo = new LockDemo();
        new Thread(() -> {
            try {
                //lockDemo.method1();
                //lockDemo.method2();
                lockDemo.method3();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "AAA").start();

        new Thread(() -> {
            try {
                //lockDemo.method1();
                //lockDemo.method2();
                lockDemo.method3();
                System.out.println(Thread.currentThread().getName());
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "BBB").start();


    }

    public void method3() throws InterruptedException {
        if (lock.tryLock(2, TimeUnit.SECONDS)) {
            try {
                System.out.println("lock = " + lock);
                TimeUnit.SECONDS.sleep(3);
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println("未抢到锁");
        }
    }

    public void method1() {

        lock.lock();
        try {
            System.out.println("lock = " + lock);
        } finally {
            lock.unlock();
        }

    }

    public void method2() {
        if (lock.tryLock()) {
            try {
                System.out.println("lock = " + lock);
            } finally {
                lock.unlock();
            }
        } else {
            System.out.println("未抢到锁");
        }
    }

}
